﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using LogLib;
using AppDataStruct;
using EECMISWS;
using System.Threading.Tasks;
using System.Threading;
using KWindow.KPageCore;
using ComLib.ComFun;

namespace YSLPages
{
    public partial class PageCaptureFinger : PageControlBase
    {
        private DeviceControl _device = null;
        private WebDataAccess _webAccess = null;
        //private IDCardAll _cardInfo = null;
        private PreApplyInfo _appInfo = null;

        private bool HZChecked = false;

        private bool SCZChecked = false;

        private bool DLZChecked = false;

        private PictureBox pbxGif = null;

        //private Label labelInputTip = null;

        //private Button buttonInputID = null;

        private Panel panelFingerCapture = null;

        private string fingerYwbh = "";
        /// <summary>
        /// 一所生物特征采集窗体句柄
        /// </summary>
        IntPtr fingerCapHwnd;
        FingerprintManage fingerMan = new FingerprintManage();

        private bool InWorking = false;

        public PageCaptureFinger()
        {
            InitializeComponent();
            SetProcessBase(ProcessCaptureFinger.Instance);
        }

        private void GetControls()
        {

        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            pbxGif = GetControl<PictureBox>("pbxGif") as PictureBox;
            //labelInputTip = GetControl<Label>("labelInputTip") as Label;
            //buttonInputID = GetControl<Button>("buttonInputID") as Button;
            panelFingerCapture = GetControl<Panel>("panelFingerCapture") as Panel;

            //labelInputTip.Parent = pictureBox1;
            //buttonInputID.Parent = pictureBox1;
            //countdownControl1.Parent = pictureBox1;
            //SetButtonDefaultStyles(buttonHome);
            //buttonNext.Parent = pictureBox1;
            //buttonHome.Parent = pictureBox1;
            //buttonLast.Parent = pictureBox1;
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            InWorking = true;
            _webAccess = WebDataAccess.Instance;
            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");
            if (Process.ContainsKey("HZChecked"))
            {
                HZChecked = Process.GetValue<bool>("HZChecked");
            }
            else
            {
                HZChecked = false;
            }
            if (Process.ContainsKey("DLZChecked"))
            {
                DLZChecked = Process.GetValue<bool>("DLZChecked");
            }
            else
            {
                DLZChecked = false;
            }
            if (Process.ContainsKey("SCZChecked"))
            {
                SCZChecked = Process.GetValue<bool>("SCZChecked");
            }
            else
            {
                SCZChecked = false;
            }
            _device = new DeviceControl("TopCamera");
            _device.OnCatchException = OnCatchException;
            _device.OnWorkingDone = OnCapSuccess;
            _device.OnWorkingFailed = OnCapFailed;
            _device.OnTimeout = OnCapTimeout;
            _device.Init();
        }

        private void OnCapTimeout(string outParams)
        {
            //throw new NotImplementedException();
        }

        private void OnCapFailed(string outParams, string errorMsg)
        {
            //throw new NotImplementedException();
        }

        private void OnCapSuccess(string outParams)
        {
            Log.WriteAsync(string.Format("拍照成功，路径：{0}", outParams));
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            //SFZInfo info = new SFZInfo();
            //info.Address = _cardInfo.address;
            //info.BirthDate = _cardInfo.birthday;
            //info.ExpiryDate = _cardInfo.validtermOfStart + "-" + _cardInfo.validtermOfEnd;
            //info.HeaderPicturePath = _cardInfo.HeadImage;
            //info.IsManualInputNumberVerify = _cardInfo.IsManualInputNumberVerify;
            //info.IssueUnit = _cardInfo.signdate;
            //info.Name = _cardInfo.name;
            //info.Nation = _cardInfo.people;
            //info.Sex = _cardInfo.sex;
            //info.SFZH = _cardInfo.number;
            //Process.SetValue("SFZInfo", info);
            //string personDir = _config.OutputDirs[_cardInfo.number];
            //Process.SetValue("PersonDataDirectory", personDir);
        }

        private bool GetYWBH()
        {
            if (HZChecked && string.IsNullOrEmpty(_appInfo.HZSQ.YWBH))  //如果采集指纹，在这之前就获取过业务编号了
            {
                if (_webAccess.Enabled)
                {
                    string ywbh_hz = _webAccess.MakeYWBH();
                    if (string.IsNullOrEmpty(ywbh_hz))
                    {
                        return false;
                    }
                    else
                    {
                        _appInfo.HZSQ.YWBH = ywbh_hz;
                        fingerYwbh = ywbh_hz;
                        Log.WriteAsync("护照申请业务编号获取成功:" + ywbh_hz);
                    }
                }
                else
                {
                    _appInfo.HZSQ.YWBH = string.Format("H{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
                    fingerYwbh = _appInfo.HZSQ.YWBH;
                    Log.WriteAsync("模拟护照申请业务编号获取成功:" + _appInfo.HZSQ.YWBH);
                }

            }
            if (SCZChecked && string.IsNullOrEmpty(_appInfo.SCZSQ.YWBH))
            {
                if (_webAccess.Enabled)
                {
                    string ywbh_scz = _webAccess.MakeYWBH();
                    if (string.IsNullOrEmpty(ywbh_scz))
                    {
                        return false;
                    }
                    else
                    {
                        _appInfo.SCZSQ.YWBH = ywbh_scz;
                        fingerYwbh = ywbh_scz;
                        Log.WriteAsync("港澳证申请业务编号获取成功:" + ywbh_scz);
                    }
                }
                else
                {
                    _appInfo.SCZSQ.YWBH = string.Format("S{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
                    fingerYwbh = _appInfo.SCZSQ.YWBH;
                    Log.WriteAsync("模拟港澳证申请业务编号获取成功:" + _appInfo.SCZSQ.YWBH);
                }
            }
            if (DLZChecked && string.IsNullOrEmpty(_appInfo.DLZSQ.YWBH))
            {
                if (_webAccess.Enabled)
                {
                    string ywbh_dlz = _webAccess.MakeYWBH();
                    if (string.IsNullOrEmpty(ywbh_dlz))
                    {
                        return false;
                    }
                    else
                    {
                        _appInfo.DLZSQ.YWBH = ywbh_dlz;
                        fingerYwbh = ywbh_dlz;
                        Log.WriteAsync("大陆证申请业务编号获取成功:" + ywbh_dlz);
                    }
                }
                else
                {
                    _appInfo.DLZSQ.YWBH = string.Format("D{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
                    fingerYwbh = _appInfo.DLZSQ.YWBH;
                    Log.WriteAsync("模拟大陆证申请业务编号获取成功:" + _appInfo.DLZSQ.YWBH);
                }
            }
            return true;
        }

        private void StartCapture()
        {
            if (!GetYWBH())
            {
                MessageBox.Show("获取业务编号失败");
                return;
            }

            if (string.IsNullOrEmpty(fingerYwbh))
            {
                MessageBox.Show("请输入业务编号");
                return;
            }

            Task task = new Task(() =>
            {
                try
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        fingerCapHwnd = fingerMan.OpenFingerprint();
                        if (fingerCapHwnd != IntPtr.Zero)
                        {
                            WinAPI.MoveWindow(fingerCapHwnd, -330, -100, 1024, 768, true);
                            WinAPI.SetParent(fingerCapHwnd, panelFingerCapture.Handle);
                            fingerMan.StartFingerprintGather(fingerCapHwnd, fingerYwbh, CaptureStatusCallBack);
                        }
                        else
                        {
                            fingerMan.KillFingerprint();
                            Log.WriteAsync("初始化指纹仪失败");
                            if (InWorking)
                            {
                                Process.ToNext();
                            }
                        }
                    }));
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            });
            task.Start();
        }

        int lastFingerCode = 0;//最后一次返回的指位信息
        private void SwitchGif(int fingerCode)
        {
            if (fingerCode == lastFingerCode)
                return;
            string AssemblyDirectory = GetAssemblyDirectory();
            lastFingerCode = fingerCode;
            SetPictureBoxVisible(pbxGif, true);
            switch (fingerCode)
            {
                case 1:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\右拇指按下.gif"));
                    break;
                case 2:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\右食指按下.gif"));
                    break;
                case 3:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\右中指按下.gif"));
                    break;
                case 4:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\右环指按下.gif"));
                    break;
                case 5:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\右小指按下.gif"));
                    break;
                case 6:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\左拇指按下.gif"));
                    break;
                case 7:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\左食指按下.gif"));
                    break;
                case 8:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\左中指按下.gif"));
                    break;
                case 9:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\左环指按下.gif"));
                    break;
                case 10:
                    UpdatePictureBox(pbxGif, Path.Combine(AssemblyDirectory, @"image\gif\左小指按下.gif"));
                    break;
            }
        }

        int curCode = 0;
        private void CaptureStatusCallBack(int code, string msg)
        {
            if (code > 0)
            {
                if (curCode != code)
                {
                    Log.WriteAsync("CaptureStatusCallBack,code:" + code.ToString() + " msg:" + msg);
                    _device.Do();
                    curCode = code;
                }

                SwitchGif(code);
            }
            else if (code == 0)
            {
                StopCapture();
                //MessageBox.Show("采集成功");
                Log.WriteAsync("采集成功");
                //pbxGif.Visible = false;
                SetPictureBoxVisible(pbxGif, false);
                GetFingerData(fingerYwbh);
                UpdateData();
                ClearData();
                Process.ToNext();
            }
            else
            {
                //MessageBox.Show("采集失败:" + msg);
                StopCapture();
                //pbxGif.Visible = false;
                SetPictureBoxVisible(pbxGif, false);
                ClearData();
                Process.ToNext();
            }

        }

        string _strMessage = "";
        private bool GetFingerData(string ywbh)
        {
            try
            {
                string fingerPath = "D:\\FingerData";
                if (!Directory.Exists(fingerPath))
                {
                    Directory.CreateDirectory(fingerPath);
                }

                if (string.IsNullOrEmpty(ywbh))
                {
                    _strMessage = "业务编号为空.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }

                //指纹图像文件
                string[] wsqFiles = Directory.GetFiles(fingerPath + "\\DATA", ywbh + "*.WSQ");
                if (wsqFiles.Length <= 0)
                {
                    _strMessage = "找不到指纹图像文件.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }
                string wsqFile = wsqFiles[0];
                if (!File.Exists(wsqFile))
                {
                    _strMessage = "指纹图像文件不存在.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }

                //指纹模板文件
                string[] tplFiles = Directory.GetFiles(fingerPath + "\\DATA", ywbh + "*.TPL");
                if (tplFiles.Length <= 0)
                {
                    _strMessage = "找不到指纹模板文件.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }
                string tplFile = tplFiles[0];
                if (!File.Exists(tplFile))
                {
                    _strMessage = "指纹模板文件不存在.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }

                //异常描述文件
                string[] errFiles = Directory.GetFiles(fingerPath + "\\DATA", ywbh + "*.ERR");
                if (errFiles.Length <= 0)
                {
                    _strMessage = "找不到异常描述文件.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }
                string errFile = errFiles[0];
                if (!File.Exists(errFile))
                {
                    _strMessage = "异常描述文件不存在.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }

                //MD5文件
                string[] md5Files = Directory.GetFiles(fingerPath + "\\DATA", ywbh + "*.MD5");
                if (md5Files.Length <= 0)
                {
                    _strMessage = "找不到MD5文件.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }
                string md5File = md5Files[0];
                if (!File.Exists(md5File))
                {
                    _strMessage = "MD5文件不存在.";
                    Log.WriteAsync(_strMessage);
                    return false;
                }


                byte[] bWsqFile = Common.DatToByte(wsqFile);
                string wsqFileName = Path.GetFileNameWithoutExtension(wsqFile);
                if (bWsqFile != null && bWsqFile.Length > 0)
                {
                    string fileBase64 = Common.ByteToBase64String(bWsqFile);
                    if (HZChecked)
                    {
                        _appInfo.HZSQ.WSQ = fileBase64;
                        _appInfo.HZSQ.WSQ_File = _appInfo.HZSQ.YWBH + wsqFileName.Substring(15);
                    }

                    if (SCZChecked)
                    {
                        _appInfo.SCZSQ.WSQ = fileBase64;
                        _appInfo.SCZSQ.WSQ_File = _appInfo.SCZSQ.YWBH + wsqFileName.Substring(15);
                    }


                    if (DLZChecked)
                    {
                        _appInfo.DLZSQ.WSQ = fileBase64;
                        _appInfo.DLZSQ.WSQ_File = _appInfo.DLZSQ.YWBH + wsqFileName.Substring(15);
                    }
                }

                byte[] bTplFile = Common.DatToByte(tplFile);
                string tplFileName = Path.GetFileNameWithoutExtension(tplFile);
                if (bTplFile != null && bTplFile.Length > 0)
                {
                    string fileBase64 = Common.ByteToBase64String(bTplFile);
                    if (HZChecked)
                    {
                        _appInfo.HZSQ.TPL = fileBase64;
                        _appInfo.HZSQ.TPL_File = _appInfo.HZSQ.YWBH + tplFileName.Substring(15);
                    }


                    if (SCZChecked)
                    {
                        _appInfo.SCZSQ.TPL = fileBase64;
                        _appInfo.SCZSQ.TPL_File = _appInfo.SCZSQ.YWBH + tplFileName.Substring(15);
                    }
                    if (DLZChecked)
                    {
                        _appInfo.DLZSQ.TPL = fileBase64;
                        _appInfo.DLZSQ.TPL_File = _appInfo.DLZSQ.YWBH + tplFileName.Substring(15);
                    }
                }

                byte[] bErrFile = Common.DatToByte(errFile);
                string errFileName = Path.GetFileNameWithoutExtension(errFile);
                if (bErrFile != null && bErrFile.Length > 0)
                {
                    string fileBase64 = Common.ByteToBase64String(bErrFile);
                    if (HZChecked)
                    {
                        _appInfo.HZSQ.ERR = fileBase64;
                        _appInfo.HZSQ.ERR_File = _appInfo.HZSQ.YWBH + errFileName.Substring(15);
                    }

                    if (SCZChecked)
                    {
                        _appInfo.SCZSQ.ERR = fileBase64;
                        _appInfo.SCZSQ.ERR_File = _appInfo.SCZSQ.YWBH + errFileName.Substring(15);
                    }

                    if (DLZChecked)
                    {
                        _appInfo.DLZSQ.ERR = fileBase64;
                        _appInfo.DLZSQ.ERR_File = _appInfo.DLZSQ.YWBH + errFileName.Substring(15);
                    }
                }

                byte[] bMd5File = Common.DatToByte(md5File);
                string md5FileName = Path.GetFileNameWithoutExtension(md5File);
                if (bMd5File != null && bMd5File.Length > 0)
                {
                    string fileBase64 = Common.ByteToBase64String(bMd5File);
                    if (HZChecked)
                    {
                        _appInfo.HZSQ.MD5 = fileBase64;
                        _appInfo.HZSQ.MD5_File = _appInfo.HZSQ.YWBH + md5FileName.Substring(15);
                    }

                    if (SCZChecked)
                    {
                        _appInfo.SCZSQ.MD5 = fileBase64;
                        _appInfo.SCZSQ.MD5_File = _appInfo.SCZSQ.YWBH + md5FileName.Substring(15);
                    }
                    if (DLZChecked)
                    {
                        _appInfo.DLZSQ.MD5 = fileBase64;
                        _appInfo.DLZSQ.MD5_File = _appInfo.DLZSQ.YWBH + md5FileName.Substring(15);
                    }
                }

                string strLog = string.Format("指纹信息{0}{1}, 业务编号:{2}", wsqFile, _strMessage, ywbh);
                Log.WriteAsync(strLog);
                return true;
            }
            catch (Exception ex)
            {
                _strMessage = "获取指纹信息时发生异常：" + ex.Message;
                Log.WriteAsync(_strMessage);
                Log.WriteException(ex.ToString());
                return false;
            }
        }
        private void StopCapture()
        {
            if (null != pbxGif)
                SetPictureBoxVisible(pbxGif, false);
            //pbxGif.Visible = false;

            fingerMan.KillFingerprint();
        }
        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            if (_device != null)
            {
                _device.Stop();
                _device.Dispose();
                _device = null;
            }
            InWorking = false;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            //Speak("请把本人身份证放置于身份证阅读区");
            StartCapture();
        }

        public override void StopWork()
        {
            base.StopWork();
            StopCapture();
        }

        //private void OnReadSuccess(string outParams)
        //{
        //    string msg = string.Format("读取结果: \n{0}", outParams);
        //    Log.WriteAsync(msg);

        //    // 在这里处理身份证信息解析结果
        //    //_cardInfo = JsonConvert.DeserializeObject<IDCardAll>(outParams);
        //    Action<string> handler = (e) =>
        //    {
        //        UpdateData();
        //        ClearData();
        //        Process.ToNext();
        //    };
        //    this.Invoke(handler, msg);
        //}

        //private void OnReadFailed(string outParams)
        //{
        //    string msg = string.Format("身份证信息读取错误: \n{0}", outParams);
        //    Log.WriteAsync(msg);
        //    Action<string> handler = (e) =>
        //    {
        //        MessageBox.Show(e);
        //        ClearData();
        //        Process.ToHome();
        //    };
        //    this.Invoke(handler, msg);
        //}

        //private void OnReadTimeout(string outParams)
        //{
        //    string msg = string.Format("读取身份证信息超时: \n{0}", outParams);
        //    Log.WriteAsync(msg);
        //    Action<string> handler = (e) =>
        //    {
        //        MessageBox.Show(e);
        //        StopWork();
        //        ClearData();
        //        Process.ToHome();
        //    };
        //    this.Invoke(handler, msg);
        //}

        private void OnCatchException(string outParams)
        {
            string msg = string.Format("设备运行发生了异常: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MessageBox.Show(e);
                StopWork();
                ClearData();
                Process.ToHome();
            };
            this.Invoke(handler, msg);
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            //StopWork();
            //base.OnCountdownCompleted(sender, e);
        }

        //private void buttonInputID_Click(object sender, EventArgs e)
        //{
        //    string inputIDNumber = "";
        //    string inputXM = "";
        //    StopWork();
        //    if (StartManualInput(out inputIDNumber, out inputXM))
        //    {
        //        //_cardInfo = new IDCardAll();
        //        //_cardInfo.number = inputIDNumber;
        //        //_cardInfo.name = inputXM;
        //        //_cardInfo.birthday = IDCardCheck.GetBirthday(inputIDNumber);
        //        //_cardInfo.sex = IDCardCheck.GetSex(inputIDNumber);
        //        //_cardInfo.IsManualInputNumberVerify = true;
        //        UpdateData();
        //        ClearData();
        //        Process.ToNext();
        //    }
        //    else
        //    {
        //        StartWork();
        //    }
        //}

        //private bool StartManualInput(out string SFZH, out string XM)
        //{
        //    SFZH = "";
        //    XM = "";
        //    bool bRet = false;
        //    Log.WriteAsync("用户启动了身份证人工输入操作...");
        //    //FormInputID formInputID = new FormInputID();
        //    Speak("请输入您的身份证号码");
        //    //if (formInputID.ShowDialog() == DialogResult.OK)
        //    //{
        //    //    //SFZH = formInputID.Number;
        //    //    bRet = true;
        //    //}
        //    //else
        //    //{
        //    //    Log.WriteAsync("用户取消了人工输入...");
        //    //    bRet = false;
        //    //}
        //    //if (bRet)
        //    //{
        //    //    FormInputTool inputTool = new FormInputTool();
        //    //    if (inputTool.ShowDialog() == DialogResult.OK)
        //    //    {
        //    //        XM = inputTool.InputText;
        //    //    }
        //    //    else
        //    //    {
        //    //        bRet = false;
        //    //    }
        //    //}
        //    return bRet;
        //}

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            StopWork();
            base.btnCancel_Click(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            StopWork();
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            StopWork();
            base.btnNext_Click(sender, e);
        }
    }
}
